<template>
  <div>
    <van-nav-bar title="我的地址" left-arrow @click-left="$router.back()" />
    <div class="introduct">
      <van-address-list v-model="chosenAddressId" :list="list" :disabled-list="disabledList" disabled-text="以下地址超出配送范围"
        default-tag-text="默认" @add="onAdd" @select="select" @edit="onEdit">
        <template #item-bottom="data">
          <!-- <van-button round type="danger" text="删除" class="address-delete-button"
            @click="deleteAddress(item)" /> -->
        </template>
      </van-address-list>
    </div>
  </div>
</template>


<script setup lang="ts">
import { ref } from "vue";
import router from "@/router";
import { showToast } from "vant";
import { httpGetToken } from "@/utils/request";

const chosenAddressId = ref("1");
const list = ref([]);
const disabledList = ref([]);



const formatAddressData = (data: any) => {
  return data.map((item: any) => ({
    id: item.address_id,
    name: item.name,
    tel: item.phone,
    address: item.address,
    isDefault: item.isDefault || false,
  }));
};


//底部跳转
const onAdd = () => {
  console.log(1);
  router.push("/address");
};

const select = (item: any) => {
  console.log(item);
  router.push({
    path: '/confirm',
    query: {
      address_id: item.id,
      address: item.address,
      name: item.name,
      phone: item.tel
    }
  })
}
// //  获取自己的所有地址接口  *token   /api/address
const addressList = ref([]);
httpGetToken("/api/address", "get", {})
  .then((res: any) => {
    if (res.status === 200) {
      const formattedData = formatAddressData(res.data);
      list.value = formattedData;
    }
    console.log(addressList.value);
  });

//  获取自己的所有地址接口  *token   /api/address
// const addressList = ref([]);
// httpGetToken ("/api/address",'get',{})
// .then((res)=>{
//   if(res.status===200){
//     addressList.value=res.data
//   }
// console.log(addressList.value)
// })

//删除地址接口  *token   /api/address   delete    address_id:地址id  Delete
// const deleteAddress = (address_id: object) => {
//   console.log(list.item)
//   httpGetToken("/api/address", "delete", { address_id: address_id })
//     .then((res: any) => {
//       if (res.status === 200) {

//         httpGetToken("/api/address", "get", {})
//           .then((res: any) => {
//             if (res.status=== 200) {}
//           })
//       }
//     })
// }
const adressid = ref()
const onEdit = (item: any) => {
  console.log(item);
  adressid.value = item.address_id
  let res: any = httpGetToken("/api/address", "delete", {
    address_id: item.id,

  });
  showToast({ message: "删除成功" });
  router.push("/confirm")
  if (res.status === 200) {
    addressList.value = addressList.value.filter(
      (item: any) => item.address_id !== item.address_id
    );
  }
}


</script>


<style scoped>
.btn {
  margin-top: 20px;
  margin-left: 50px;
}
</style>